package com.example.socialwebserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.socialwebserver.mapper.MessageMapper;
import com.example.socialwebserver.pojo.CommunicateDTO;
import com.example.socialwebserver.pojo.MessageDAO;
import com.example.socialwebserver.pojo.MessageDTO;
import com.example.socialwebserver.pojo.MessageVO;
import com.example.socialwebserver.service.MessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageMapper messageMapper;
    @Override
    public List<MessageVO> selectNotRead(CommunicateDTO messageDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("to_user",messageDTO.getToUser());
        queryWrapper.eq("from_user",messageDTO.getFromUser());
        queryWrapper.eq("read_or_not",0);
        List<MessageDAO> list = messageMapper.selectList(queryWrapper);
        ArrayList<MessageVO> messageList = new ArrayList<MessageVO>();
        for(MessageDAO messageDAO:list)
        {
            MessageVO messageVO = new MessageVO();
            BeanUtils.copyProperties(messageDAO,messageVO);
            messageList.add(messageVO);
        }
        MessageDAO messageDAO = new MessageDAO();
        messageDAO.setReadOrNot(1);
        int update = messageMapper.update(messageDAO, queryWrapper);//将信息设置为已读，1代表已读
        return messageList;
    }

    @Override
    public List<MessageVO> selectAll(CommunicateDTO messageDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("to_user",messageDTO.getToUser());
        queryWrapper.eq("from_user",messageDTO.getFromUser());
        List<MessageDAO> list = messageMapper.selectList(queryWrapper);
        ArrayList<MessageVO> messageList = new ArrayList<MessageVO>();
        for(MessageDAO messageDAO:list)
        {
            MessageVO messageVO = new MessageVO();
            BeanUtils.copyProperties(messageDAO,messageVO);
            messageList.add(messageVO);
        }
        MessageDAO messageDAO = new MessageDAO();
        messageDAO.setReadOrNot(1);
        messageMapper.update(messageDAO,queryWrapper);//将信息设置为已读，1代表已读
        return messageList;
    }

    @Override
    public boolean insertMessage(MessageDTO messageDTO) {
        MessageDAO messageDAO = new MessageDAO();
        BeanUtils.copyProperties(messageDTO,messageDAO);
        int res = messageMapper.insert(messageDAO);
        return res > 0;
    }
}
